try {
//var io = undefined; 
var SuperSensor = {
    // Application Constructor
	  compteur		: 0
	, compteurGeo	: 0 
	, nomEtat		: 'bonjour'
	, nomPosition	: 'salut'
    , initialize: function() {
		 var self = this;
         document.addEventListener('deviceready', function() {self.onDeviceReady();}, false);
		}
	, loadSocketIo	: function(ws) {
		 var self = this;
		 try {
			 self.socket = io.connect(ws);
			 self.log("Socket done...");
			} catch(err) {self.error("Error with IO", err, ". retrying in 1s");
						  setTimeout(function() {self.loadSocketIo(ws);}, 1000);
						 }

		}
    , onDeviceReady	: function() {
		 var self = this;		 
		 this.TabX = [];
		 this.TabY = [];
		 this.TabZ = [];	
		 this.polyX = document.getElementById('accx');	
		 this.polyY = document.getElementById('accy');			 
		 this.polyZ = document.getElementById('accz');			 		 
		 this.debug = document.getElementById('Debug');
		 this.debugGeo = document.getElementById('DebugGeo');
		 //document.getElementById("courbes").setAttribute('transform', scale(1,10));
		 this.log('Start...');
		 this.dtBackgroundService = 5000;
		 
		 // document.getElementById('courbes').setAttribute('transform', 'scale(1,10)');
		 this.svgCanvas = document.getElementById('svgCanvas');
		 document.getElementById('courbes').setAttribute('transform', 'translate(0, 150)');
		 this.courbeScale = 10;
		 this.currentEtat = '';
		 
		 // Start watching accelerometer
		 try {
			 var btScan = document.getElementById('QrScanner');
			 btScan.addEventListener('click', function() {self.QRscan();}, false);
			 this.accWatchId = navigator.accelerometer.watchAcceleration( function(acc) {self.updateAcceleration(acc);}
													  , function(err) {self.error('Acceleration error', err);}
													  , { frequency: 50 }
													  );
			} catch(err) {this.error('Error initializing accelerometer', err);}
		 this.log('Gogogo !');
		 
		 try {this.log('watchPosition');
			  navigator.geolocation.getCurrentPosition( function(geo) {self.updateGeolocalisation(geo);}
															, function(err) {self.log('error geo'); self.errorGeo('Geolocalisation error', err.code, ' : ', err.message);}
															, { frequency: 1000 }
															);
			  this.geoWatchID = navigator.geolocation.watchPosition( function(geo) {self.updateGeolocalisation(geo);}
															, function(err) {self.log('error geo'); self.errorGeo('Geolocalisation error', err.code, ' : ', err.message);}
															, { frequency: 1000 }
															);
			 this.log('watchPosition => ', this.geoWatchID);
			} catch(err) {this.errorGeo('Error initializing Geolocalisation', err);}
			this.log('Gogogo !');
		 
		 
		
		 // test pour la batterie et les boutons
		 
		try{
			document.addEventListener("batterystatus", function(info) {self.onBatteryStatus(info);}, false); 
			// Si un pb, essayer avec :
			// window.addEventListener("batterystatus", function(info) {self.onBatteryStatus(info);}, false); 
			} catch(err) {this.error('Error initializing battery', err);}
		try{
			document.addEventListener("volumedownbutton", function() {self.log('down'); self.onVolumeDownKeyDown();}, false);
			} catch(err) {this.error('Error initializing volumedownbutton', err);}
			
		try{
			document.addEventListener("volumeupbutton", function() {self.onVolumeUpKeyDown();}, false);
			} catch(err) {this.error('Error initializing volumeupbutton', err);}		
		try {
			 nfc.addNdefListener( function(evt) {
										 var str = "";
										 for(var i in evt.tag) {
											 str += '   ' + i + ' : ' + evt.tag[i];
											 str += "\n";
											}
										 self.log('NFC : ', str);
										} // Callback
							    , function() {self.log('NFC activated');} // Callback register success
								, function(err) {self.log('NFC failed : ', err);} // Callback register failure
								);
			} catch(err) {self.log("Gros crache de l'initialisation du NFC (le plugin a-t-il été intégré au projet ?) : ", err);}
		try {
			 var srv = cordova.plugins.myService, self = this;
			 srv.getStatus( function(data){
								 if (data.ServiceRunning) {
									self.enableTimer(data);
								   } else {
									  srv.startService(function(r){self.enableTimer(r)}, function(e){self.error("Error starting the background service", e)});
								   }
								}
						  , function(e){self.error("Impossible to get background service status : ", e);}
						  );
			} catch(err) {self.error("Error initializing background service");}
		try {window.addEventListener('deviceorientation', function(eventData) {
				 // self.log("Orientation(", eventData.gamma, ';', eventData.beta, ';', eventData.alpha, ')');
				}, false );
			} catch(err) {self.error("Error initializing orientation service");}
		/*
		try{
			document.addEventListener("StartCallKeyDown", function() {self.onStartCallKeyDown();} false);
			} catch(err) {this.error('Error initializing StartCallKeyDown', err);}		
		
		try{
			document.addEventListener("onEndCallKeyDown", function() {self.EndCallKeyDown();} false);
			} catch(err) {this.error('Error initializing onEndCallKeyDown', err);}	
		*/
		}
	, enableTimer	: function(data) {
		 var srv = cordova.plugins.myService, self = this;
		 if (data.TimerEnabled) {
			 this.log("Background service launched...");
			} else {srv.enableTimer(this.dtBackgroundService, function(r){self.enableTimer(r)}, function(e){self.error("Error enabling background service timer : ", e)});
		  }
		}
		
		
    // Update DOM on a Received Event
	, QRscan				: function() {
		try {
		var self = this;
		cordova.plugins.barcodeScanner.scan(
			  function (result) {
				self.log("QR code : ", result.text);
				if(result.text.indexOf("AppsGate://") === 0) {
					 // Establish connexion ?
					 var ws = 'http' + result.text.substring(8);
					 self.log("Connect to ", ws);
						 var socketNode = document.getElementById('SocketIoScript');
						 if(!socketNode) {
							 socketNode = document.createElement('script');
							 document.head.appendChild( socketNode );
							 socketNode.onload = function() {self.log('SocketIO loaded!'); self.loadSocketIo(ws);}
							 socketNode.setAttribute('src', ws + '/socket.io/socket.io.js');
							 self.log( socketNode.getAttribute('src') );
							 
							 // Pipo image
							 var img = document.createElement('img');
							 img.setAttribute('width', '100px');
							 img.setAttribute('height', '100px');
							 img.setAttribute('src', ws + '/pipo.svg');
							 document.body.appendChild( img );
							 
							 /* setTimeout
							 setTimeout ( function() {self.loadSocketIo(ws);}
										, 1000 );*/
							}
					}
			  }, 
			  function (error) {
				  alert("Scanning failed: " + error);
			  }
			);
			} catch(err) {this.error('Error initializing Qr scanner', err);}
		}
		
    , updateAcceleration	: function(acc) {
		 try {
			 // this.log("valeur X : " + acc.x.toFixed(2) + " ","valeur Y : " + acc.y.toFixed(2) + " ","valeur Z : " + acc.z.toFixed(2));
			 var newEtat = this.etat(acc);
			 if( newEtat != this.currentEtat && newEtat !== 'mouvement') {
				 this.log( newEtat );
				 this.currentEtat = newEtat;
				}
			 
			 this.TabX.push(acc.x);
			 this.TabY.push(acc.y);
			 this.TabZ.push(acc.z);
			 var pointsX = '';
			 var pointsY = '';
		     var pointsZ = '';
			 if(this.TabX.length > parseInt(window.getComputedStyle(this.svgCanvas).width) ) {
				 this.TabX.splice(0,1);
				 this.TabY.splice(0,1);
				 this.TabZ.splice(0,1);
				 // this.log('splice', window.getComputedStyle(this.svgCanvas).width);
				}
			 for(var i in this.TabX) {
				 pointsX += i + ',' + this.TabX[i]*this.courbeScale + ' ';
				}
			 this.polyX.setAttribute('points', pointsX);
			 
			for(var i in this.TabY) {
				 pointsY += i + ',' + this.TabY[i]*this.courbeScale + ' ';
				}
			 this.polyY.setAttribute('points', pointsY);
			 
			for(var i in this.TabZ) {
				 pointsZ += i + ',' + this.TabZ[i]*this.courbeScale + ' ';
				}
			 this.polyZ.setAttribute('points', pointsZ);			 
			 
			 
			 } catch(err) {this.error('updateAcceleration', err);}
		}
	, updateGeolocalisation		: function(geo) {
		try{
			this.log("Longitude : " + geo.coords.longitude + " ","Latitude : " + geo.coords.latitude);
			} catch(err) {this.errorGeo('updateGeolocalisation',err);}
		}
	, etat	: function(acc) {
		if(Math.sqrt((acc.x*acc.x) + (acc.y*acc.y) + (acc.z*acc.z)) < 9.85) {
			this.nomEtat = "repos";
		}
		else
			this.nomEtat = "je bouge";
		if(nomEtat = "repos" && acc.z < -9) 
		{
			this.nomPosition = "ventre";
		}
		else if(nomEtat = "repos" && acc.z > 9.3) 
		{
			this.nomPosition = "dos";
		}
		else if(nomEtat = "repos" && acc.x >8.35 || acc.x < -8.35)
		{
			this.nomPosition = "paysage";
		}
		else if(nomEtat = "repos" && acc.y > 8.5 || acc.y < -8.5)
		{
			this.nomPosition = "portrait";
		}
		else
			this.nomPosition = "mouvement";
		//return this.nomEtat;
		return this.nomPosition;
	}
	

	//test pour la batterie et bouton 	
	, onBatteryStatus :   function (info) {
		this.log("Level: " + info.level + " isPlugged: " + info.isPlugged); 
    }
	
	, onVolumeDownKeyDown : function () {
		this.log("onVolumeDownKeyDown"); 
    }
	
	, onVolumeUpKeyDown : function () {
		this.log("onVolumeUpKeyDown"); 
    }
	
	, onStartCallKeyDown  : function() {
		this.log("StartCallKeyDown"); 	
    } 
	
	, onEndCallKeyDown : function() {
		this.log("EndCallKeyDown"); 	
    } 
	
	, debugConsole	: function(classes, args) {
		 var node = document.createElement('p'), a;
			for(var i in classes) {node.classList.add(classes[i]);}
		 var compteur = document.createElement('span');
			compteur.classList.add('compteur');
			compteur.innerText = (this.compteur++) + ': ';
			node.appendChild( compteur );
		 for(var i in args) {
			 a = document.createElement('span');
			 a.innerText = args[i];
			 node.appendChild(a);
			}
		 if(this.debug.children.length) {
			 this.debug.insertBefore(node, this.debug.children[0]);
			} else {this.debug.appendChild(node);}
		}
	, log	: function() {
		 this.debugConsole(['log', 'infos'], arguments);
		 if(this.socket) {
			 // this.debugConsole(['log', 'infos'], 'Emited on socket.io');
			 this.socket.emit('log', {args: arguments});
			}
		}
	, error	: function() {
		 this.debugConsole(['log', 'error'], arguments);
		}
};

SuperSensor.initialize();

} catch(err) {alert('Error loading SuperSensor.js : ', err);}